package com.tanhua.server.service.impl;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.RecommendVideo;
import com.tanhua.model.mongo.UserFocus;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.MqMessageService;
import com.tanhua.server.service.SmallVideosService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wjs
 * @version 1.0
 * @date 2022/1/2 0002 下午 6:34
 */

@Service
public class SmallVideosServiceImpl implements SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private RecommendVideoApi recommendVideoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    @DubboReference
    private UserFocusApi userFocusApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Override
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        if (videoFile.isEmpty() || videoThumbnail.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }

        //上传视频文件到FastDFS
        String filename = videoFile.getOriginalFilename();  // abc.mp4
        String fileLastName = filename.substring(filename.lastIndexOf(".") + 1);
        //上传视频返回Url
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), fileLastName, null);
        //拼接路径
        String videoUrl = webServer.getWebServerUrl() + storePath;

        //上传图片到阿里云OSS
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

        //构建Videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API保存数据
        String videoId = videoApi.save(video);
        if (videoId == null || videoId.length() == 0) {
            throw new BusinessException(ErrorResult.error());
        }

        //发送消息
        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0301","video",videoId);
    }

    @Override
    public PageResult queryVideoList(Integer page, Integer pagesize) {

        //获取RecommendVideo推荐视频集合
        List<RecommendVideo> recommendVideos = recommendVideoApi.queryRecommendVideoList(page, pagesize, UserHolder.getUserId());
        if (recommendVideos.size() == 0) {
            recommendVideos = recommendVideoApi.RandomRecommendVideoList(pagesize, UserHolder.getUserId());
        }

        //获取RecommendVideo推荐视频集合中vid
        List<Long> vids = recommendVideos.stream().map(RecommendVideo::getVid).collect(Collectors.toList());

        List<Video> videos = videoApi.findByVids(vids);
        List<Long> userIds = videos.stream().map(Video::getUserId).collect(Collectors.toList());
        if (userIds == null || userIds.isEmpty()){
            return new PageResult();
        }
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);

        List<VideoVo> vos = videos.stream().filter(video -> map.get(video.getUserId()) != null)
                .map(video -> VideoVo.init(map.get(video.getUserId()), video))
                .collect(Collectors.toList());

        return new PageResult(page, pagesize, 0l, vos);
    }

    @Override
    public void saveFocus(String uid) {
        Long userId = UserHolder.getUserId();
        Boolean falg = userFocusApi.find(userId,uid);
        if (falg){
            throw new BusinessException(ErrorResult.loveError());
        }
        UserFocus userFocus = new UserFocus();
        userFocus.setUserId(userId);
        userFocus.setUserFocusId(Long.valueOf(uid));
        userFocus.setCreated(System.currentTimeMillis());

        userFocusApi.save(userFocus);
    }

    @Override
    public void removeFocus(String uid) {
        Long userId = UserHolder.getUserId();

        userFocusApi.remove(userId,uid);
    }

}
